package bitSedDemo;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-05-03
 * Time: 19:12
 */
public class MyBitSet {
    public byte[] elem;
    public int usedSize;
    public MyBitSet(){
        this.elem = new byte[1];
    }
    public MyBitSet(int n){
        this.elem = new byte[n/8+1];
    }
    public void set(int val){
        if(val < 0){
            throw new ArrayIndexOutOfBoundsException();
        }
        int elemIndex = val/8;
        if(elemIndex > elem.length-1){
            elem = Arrays.copyOf(elem , elemIndex+1);
        }
        int bitIndex = val%8;
        if(elem[elemIndex] == (elem[elemIndex]|= 1<<bitIndex)){
            return;
        }

        elem[elemIndex] |= (1<<bitIndex);
        usedSize++;

    }
    public void reSet(int val){
        if(val < 0){
            throw new ArrayIndexOutOfBoundsException();
        }
        int elemIndex = val/8;
        int bitIndex =val%8;
        elem[elemIndex] &=~(1<<bitIndex);
        usedSize--;

    }
    public boolean get(int val){
        if(val < 0){
            throw new ArrayIndexOutOfBoundsException();
        }
        int elemIndex = val/8;
        if(elemIndex > elem.length-1){
            elem = Arrays.copyOf(elem,elemIndex+1);
        }
        int bitIndex = val%8;
        if((elem[elemIndex]&(1<<bitIndex) )!= 0) {
            return true;
        }
        return false;
    }
    public int getUsedSize(){
        return usedSize;
    }
    public void sort(){
        for (int i = 0; i < elem.length; i++) {
            for (int j = 0; j < 8; j++) {
               if((elem[i] & (1<<j)) !=0 ){
                   System.out.print(i*8+j+" ");
               }

            }
        }
    }

}
